package com.upload.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.upload.constants.UploadDownLoadConstants;
import com.upload.service.UploadHandlerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

import static com.upload.constants.UploadDownLoadConstants.UPLOAD_SUCCESS;

@RestController
@RequestMapping(value = "/file")
public class UploadController {

    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    @Autowired
    private UploadHandlerService uploadHandlerService;

    @RequestMapping(value = "/index",method = RequestMethod.GET)
    @ResponseBody
    public String index(){
        return UploadDownLoadConstants.INDEX_MESSAGE;
    }


    @RequestMapping(value = "/upload",method = {RequestMethod.POST,RequestMethod.GET})
    @HystrixCommand(fallbackMethod = "uploadFallBack")
    public String uploadFile(@RequestParam(value = "multipartFile",required = false) MultipartFile[] multipartFile) throws IOException {

        File uploadDirFile = null;

        for (MultipartFile uploadFile : multipartFile){

            if(uploadFile != null){

                logger.info("开始上传文件：{},文件大小：{}KB",uploadFile.getOriginalFilename(),uploadFile.getSize());

                uploadDirFile = new File(UploadDownLoadConstants.UPLOAD_DIR,uploadFile.getOriginalFilename());

                logger.info("保存上传文件位置："+uploadDirFile);

                uploadFile.transferTo(uploadDirFile);

                //TODO 上传服务器
//                uploadHandlerService.uploadFile(multipartFile);

            }else {
                return UploadDownLoadConstants.UPLOAD_FALLBACK;
            }
        }

        return UPLOAD_SUCCESS;
    }

    public String uploadFallBack(MultipartFile[] multipartFile){
        logger.info("文件{},上传失败",multipartFile[0].getOriginalFilename());
        return UploadDownLoadConstants.UPLOAD_FALLBACK;
    }

}
